/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.landery.modules.sinco.service.impl;

import me.landery.modules.sinco.domain.Recommend;
import me.landery.modules.system.domain.User;
import me.landery.modules.system.service.UserService;
import me.landery.modules.system.service.mapstruct.UserMapper;
import me.landery.utils.*;
import lombok.RequiredArgsConstructor;
import me.landery.modules.sinco.repository.RecommendRepository;
import me.landery.modules.sinco.service.RecommendService;
import me.landery.modules.sinco.service.dto.RecommendDto;
import me.landery.modules.sinco.service.dto.RecommendQueryCriteria;
import me.landery.modules.sinco.service.mapstruct.RecommendMapper;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author landery
* @date 2022-06-22
**/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "recommend")
public class RecommendServiceImpl implements RecommendService {

    private final RecommendRepository recommendRepository;
    private final RecommendMapper recommendMapper;

    private final UserService userService;
    private final UserMapper userMapper;
    @Override
    public Map<String,Object> queryAll(RecommendQueryCriteria criteria, Pageable pageable){
        Page<Recommend> page = recommendRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(recommendMapper::toDto));
    }

    @Override
    public List<RecommendDto> queryAll(RecommendQueryCriteria criteria){
        return recommendMapper.toDto(recommendRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public RecommendDto findById(Long id) {
        Recommend recommend = recommendRepository.findById(id).orElseGet(Recommend::new);
        ValidationUtil.isNull(recommend.getId(),"Recommend","id",id);
        return recommendMapper.toDto(recommend);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RecommendDto create(Recommend resources) {
        return recommendMapper.toDto(recommendRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Recommend resources) {
        Recommend recommend = recommendRepository.findById(resources.getId()).orElseGet(Recommend::new);
        ValidationUtil.isNull( recommend.getId(),"Recommend","id",resources.getId());
        recommend.copy(resources);
        recommendRepository.save(recommend);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            recommendRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<RecommendDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (RecommendDto recommend : all) {
            Map<String,Object> map = new LinkedHashMap<>();
//            map.put("用户id", recommend.getUid());
            map.put("推荐码", recommend.getReferCode());
            map.put("创建日期", recommend.getCreateTime());
            map.put("更新时间", recommend.getUpdateTime());
            map.put("创建者", recommend.getCreateBy());
            map.put("更新者", recommend.getUpdateBy());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RecommendDto getReferCode() {
        RecommendDto recommendDto = recommendMapper.toDto(recommendRepository.findByUserId(SecurityUtils.getCurrentUserId()));
        if (recommendDto == null){
            //如果为空新建一个
            Recommend recommend= new Recommend();
            recommend.setUser(userMapper.toEntity(userService.findById(SecurityUtils.getCurrentUserId())));
            String referCode = RandomUtil.randomString(20);
            //判断是否重复
            while (recommendRepository.findByReferCode(referCode) != null){
                referCode = RandomUtil.randomString(20);
            }
            recommend.setReferCode(referCode);
            recommend = recommendRepository.save(recommend);
            return recommendMapper.toDto(recommend);
        }
        return recommendDto;

    }

    @Override
    public Recommend getByReferCode(String referCode) {
        return recommendRepository.findByReferCode(referCode);
    }

}